# -*- coding: utf-8 -*-

import ast
import random
import socket
import struct
import string
import mimesis
import binascii


class Random():
    def __init__(self, scope: dict, index) -> None:
        self._scope = scope
        self._index = index

    def rand_base(self, keyword):
        """
            格式化前端返回数据，转为数组对象
        """
        data_range = self._scope.get(keyword)
        try:
            if isinstance(data_range, (list, tuple)):
                return data_range

            # 使用ast.literal_eval()可能会引入潜在的安全风险
            data_range_eval = ast.literal_eval(data_range)
            if isinstance(data_range_eval, (list, tuple)):
                return data_range_eval
            else:
                raise ValueError(f'参数非法：{data_range}')
        except Exception as e:
            raise ValueError(f'参数非法：{data_range}') from e

    def rand_int(self, keyword):
        int_range = self.rand_base(keyword)
        if (isinstance(int_range, list)):
            # 当返回值类型为列表时，随机选择数组中的值
            return random.randint(int_range[0], int_range[1])
        else:
            # 当返回值类型为元组时，随机值自增
            if ((int_range[0] + self._index) <= int_range[1]):
                return int_range[0] + self._index
            else:
                return random.randint(int_range[0], int_range[1])

    def rand_str(self, keyword):
        """
        随机生成字符串
        """
        # 生成包含大小写字母和数字的所有字符集合
        characters = string.ascii_letters + string.digits
        # 从字符集合中随机选取length个字符，并拼接成字符串
        return ''.join(random.choices(characters, k=self.rand_int(keyword)))

    def rand_hex(self, keyword):
        """
        随机生成16进制格式字符串
        """
        byte_string = self.rand_str(keyword).encode('utf-8')
        hex_string = binascii.hexlify(byte_string).decode('utf-8')
        hex_string_with_spaces = ' '.join(
            hex_string[i:i+2] for i in range(0, len(hex_string), 2))
        return hex_string_with_spaces

    def rand_ip(self, keyword):
        return socket.inet_ntoa(struct.pack('>I', self.rand_int(keyword)))

    def rand_ipv6(self, keyword):
        binary = self.rand_int(keyword).to_bytes(16, byteorder='big')
        return socket.inet_ntop(socket.AF_INET6, binary)

    def rand_mac(self, keyword):
        mac_parts = [self.rand_int(keyword) for _ in range(6)]
        mac_address = ':'.join(map(lambda x: "%02x" % x, mac_parts))
        return mac_address

    def rand_choice(self, keyword):
        choice_range = self.rand_base(keyword)
        return random.choice(choice_range)


def generate_str(k: str, *args, **kwargs):
    """生成规则"""
    rules = []
    temp = string.Template(k)
    ids_range = ast.literal_eval(kwargs.get('id'))
    for i, j in enumerate(range(ids_range[0], ids_range[1] + 1)):
        rand = Random(scope=kwargs, index=i)
        rule = temp.substitute(
            id=j,
            symbol=rand.rand_choice('symbol'),
            symbol1=rand.rand_choice('symbol'),
            symbol2=rand.rand_choice('symbol'),
            int=rand.rand_int('int'),
            int1=rand.rand_int('int'),
            int2=rand.rand_int('int'),
            str=rand.rand_str('str'),
            str1=rand.rand_str('str'),
            str2=rand.rand_str('str'),
            hex=rand.rand_hex('hex'),
            hex1=rand.rand_hex('hex'),
            hex2=rand.rand_hex('hex'),
            sip=rand.rand_ip('ip'),
            dip=rand.rand_ip('ip'),
            sipv6=rand.rand_ipv6('ipv6'),
            dipv6=rand.rand_ipv6('ipv6'),
            sport=rand.rand_int('port'),
            dport=rand.rand_int('port'),
            smask=rand.rand_int('mask'),
            dmask=rand.rand_int('mask'),
            smac=rand.rand_mac('mac'),
            dmac=rand.rand_mac('mac'),
            proto=rand.rand_choice('proto'),
            direc=rand.rand_choice('direc'),
            offset=rand.rand_int('offset'),
            action=rand.rand_choice('action'),
            regex=rand.rand_choice('regex'),
            meta=rand.rand_choice('meta'),
        ) + '\n'
        rules.append(rule)
    return ''.join(rules)
